package org.hncors.gnssparse;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.southgnss.connect.DataLinkerType;
import com.southgnss.connect.DeviceParManage;
import com.southgnss.connect.TopDeviceManage;

import org.hncors.gnssparse.base.BaseExitActivity;
import org.hncors.gnssparse.base.MyApplication;
import org.hncors.gnssparse.fragement.GnssListFragment;
import org.hncors.gnssparse.fragement.GnssMapFragment;
import org.hncors.gnssparse.fragement.HomeFragment;
import org.hncors.gnssparse.fragement.MineFragment;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseExitActivity {

    private static final String TAG = "MAIN ACTIVITY";
    private LayoutInflater layoutInflater;
    private FragmentTabHost mTabHost;
    private final Class fragmentArray[] = {HomeFragment.class, GnssMapFragment.class, GnssListFragment.class, MineFragment.class};
    private int mTitleArray[] = {R.string.tab_home, R.string.tab_gnss_map,R.string.tab_gnss_list,R.string.tab_mine};
    private int mImageViewArray[] = {R.drawable.main_home_icon_selector, R.drawable.main_cars_icon_selector,
            R.drawable.main_msg_icon_selector,R.drawable.main_mine_icon_selector};
    private String mTextviewArray[] = {"home","car_list","messages",  "mine"};

    private String preTab = "home";
    private TextView unread;
    public static final int START_VIEW_TERMINAL = 100;
    private boolean isGranter = false;
    private final int REQUEST_PHONE_PERMISSIONS = 0;


    private String strAddress = "";
    private int connectType = 0;//0-本身，1-蓝牙
    private String mUserName = "";
    private String strName;
    private static final int PERMISSION_LOCATION = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appendMainBody(this, R.layout.activity_main);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        MyApplication.getInstance().addActivity(this);
        MyApplication.getInstance().setMain(this);
        //MyApplication.getInstance().mUser.setUid("114");

        application.setMain(this);
        initView();

    }

    private void initView() {
//        RelativeLayout base_frame = (RelativeLayout)findViewById(R.id.base_frame);
//        base_frame.getRootView().setBackgroundColor(this.getResources().getColor(R.color.background));

        layoutInflater = LayoutInflater.from(this);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.contentPanel);
        int fragmentCount = fragmentArray.length;
        for (int i = 0; i < fragmentCount; ++i) {
            //为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中

            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            mTabHost.getTabWidget().setDividerDrawable(null);
        }
        mTabHost.setCurrentTab(0);
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                Log.i(TAG,"TTTTTTTTTtttttttttttttttTTTTTID= " + tabId);
                preTab = tabId;
            }
        });
        //checkUpdate();
        checkPermission();
        requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_LOCATION);
    }

    @Override
    protected void onResume() {
        super.onResume();

        initData();
    }

    public void switchTab(int i){
        mTabHost.setCurrentTab(i);
//        initCartData();

    }

    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.home_tab, null);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        icon.setImageResource(mImageViewArray[index]);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(mTitleArray[index]);
        if(index==3){
            unread = (TextView) view.findViewById(R.id.tab_unread);

        }
        return view;
    }
    private void initData() {
        connectType = ProgramConfigWrapper.GetInstance(this).GetConnectType();
        strName = ProgramConfigWrapper.GetInstance(this).GetBluetoothName();
        strAddress = ProgramConfigWrapper.GetInstance(this).GetBluetoothAddress();
        if (DeviceParManage.GetInstance() != null) {
            mUserName = DeviceParManage.GetInstance().GetWorkParaUserName();
            ;
        }
        //  TopDeviceManage.getInstance(mActivity).setGnssInfoListener(mActivity);
    }

    public void checkPermission() {
        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION )!= PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.ACCESS_COARSE_LOCATION );
            if ((checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION  )!= PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.ACCESS_FINE_LOCATION  );
            if (permissionsList.size() == 0){
//                startRecord();
                isGranter = true;
            }else{
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_PHONE_PERMISSIONS);
            }
        }else{
//            startRecord();
            isGranter = true;
        }
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        switch (requestCode) {
//            case REQUEST_PHONE_PERMISSIONS:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    isGranter = true;
//                   // mLocClient.restart();
//                } else {
//
//                    Toast.makeText(MainActivity.this, "您需要开通权限，并重启应用！", Toast.LENGTH_LONG).show();
//                }
//                break;
//            default:
//                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//    }

    private void connect() {
        if (connectType == 0) {
            connectLocal();
        } else if (connectType == 1) {
            connectBluetooth();
        }
    }
    private void connectBluetooth() {
        if (strAddress.equals("")) {
            Toast.makeText(this, getString(R.string.please_choose_reliable_bluetooth_device), Toast.LENGTH_SHORT).show();
            return;
        }
        TopDeviceManage.getInstance(this).setDataLink(DataLinkerType.BLUETOOTH);
        TopDeviceManage.getInstance(this).connect(strAddress);
    }

    private void connectLocal() {
        if (!TopDeviceManage.getInstance(this).isGpsEnable()) {
            Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            this.startActivity(callGPSSettingIntent);
            Toast.makeText(this, getString(R.string.setting_open_gps), Toast.LENGTH_SHORT).show();
            return;
        }
        TopDeviceManage.getInstance(this).setDataLink(DataLinkerType.LOCAL);
        TopDeviceManage.getInstance(this).connect("");
    }
    /**
     * 申请权限
     *
     * @param permission
     * @param requestCode
     */
    public void requestPermission(String permission, int requestCode) {
        if (!isGranted(permission)) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                Toast.makeText(this, "该功能需要位置权限，请打开位置权限！！！", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestCode);
            }
        } else {
            connect();
        }
    }

    private boolean isGranted(String permission) {
        return !isMarshmallow() || isGranted_(permission);
    }

    private boolean isGranted_(String permission) {
        int checkSelfPermission = ActivityCompat.checkSelfPermission(this, permission);
        return checkSelfPermission == PackageManager.PERMISSION_GRANTED;
    }

    private boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    connect();
                } else {
                    Toast.makeText(this, "位置权限未打开！！！", Toast.LENGTH_SHORT).show();
                }
                return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
